package com.ccteam.admin.view.fragments.music

import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.activity.addCallback
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.fragment.app.setFragmentResult
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.ccteam.admin.R
import com.ccteam.admin.databinding.FragmentUploadAudioBinding
import com.ccteam.admin.utils.LoadMessage
import com.ccteam.admin.view.fragments.common.UploadFragment
import com.ccteam.admin.viewmodels.music.UploadAudioViewModel
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.buffer
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

/**
 * @author Xiaoc
 * @since 2021/4/24
 */
@AndroidEntryPoint
class UploadAudioFragment: Fragment() {

    private var _binding: FragmentUploadAudioBinding? = null
    private val binding get() = _binding!!

    private val uploadAudioViewModel by viewModels<UploadAudioViewModel>()

    /**
     * 选择音乐的内容
     * 选择完手机中的图片后，将其存储到ViewModel中并进行对应UI更新
     */
    private val selectAudio = registerForActivityResult(ActivityResultContracts.GetContent()) { uri ->
        uri?.let {
            uploadAudioViewModel.setAudioUri(it)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        requireActivity().onBackPressedDispatcher.addCallback(this) {
            // 如果正在处理，退出给予提示
            if(uploadAudioViewModel.isSegmenting.value != LoadMessage.Loading &&
                    uploadAudioViewModel.uploadMessage.value != LoadMessage.Loading){
                        findNavController().navigateUp()
                return@addCallback
            }
            MaterialAlertDialogBuilder(requireContext())
                .setTitle(R.string.description_attention)

                .setMessage(getString(
                    R.string.description_back_attention_info))
                .setNegativeButton(R.string.description_cancel) { _, _ ->
                }
                .setPositiveButton(R.string.description_delete) { _, _ ->
                    findNavController().navigateUp()
                }.show()
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentUploadAudioBinding.inflate(inflater,container,false)
        binding.tvLog.movementMethod = ScrollingMovementMethod.getInstance()
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

        uploadAudioViewModel.enableSelectAudioButton.observe(viewLifecycleOwner, {
            binding.btnSelectAudio.isEnabled = it
        })

        uploadAudioViewModel.enableUploadAudioButton.observe(viewLifecycleOwner, {
            binding.btnUploadAudio.isEnabled = it
        })

        uploadAudioViewModel.isSegmenting.observe(viewLifecycleOwner, {
            binding.btnSelectAudio.setLoading(it is LoadMessage.Loading)
            binding.btnUploadAudio.isEnabled = it is LoadMessage.Success
        })

        uploadAudioViewModel.uploadMessage.observe(viewLifecycleOwner, {
            binding.btnUploadAudio.setLoading(it is LoadMessage.Loading)
            if(it is LoadMessage.Success){
                setFragmentResult(UploadFragment.UPLOAD_REQUEST_KEY,
                    bundleOf(UploadFragment.UPLOAD_REQUEST_KEY to true))
                Toast.makeText(requireContext().applicationContext,requireContext().getString(R.string.description_success),Toast.LENGTH_SHORT).show()
                findNavController().navigateUp()
            }
        })

        binding.btnSelectAudio.setProgressButtonOnClickListener {
            selectAudio.launch("audio/*")
        }

        binding.btnUploadAudio.setProgressButtonOnClickListener {
            uploadAudioViewModel.uploadAudio()
        }

        uploadAudioViewModel.audioUri.observe(viewLifecycleOwner, {
            binding.tvLog.text = ""
            uploadAudioViewModel.segmentAudio()
        })

        viewLifecycleOwner.lifecycleScope.launch {
            uploadAudioViewModel.logMessage.collect {
                binding.tvLog.append(it)
                binding.scrollLog.post {
                    binding.scrollLog.smoothScrollTo(0, binding.tvLog.bottom)
                }
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()

        _binding = null
    }
}